<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\car;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\GetCardSmsLinkResponseBody\data;
use app\dao\activity\coupon\StoreCouponUserDao;
use app\dao\car\CarOrderDao;
use app\model\car\BaseCityFee;
use app\model\car\BasePlace;
use app\model\car\BaseSendFee;
use app\model\car\CarContact;
use app\model\car\CarDate;
use app\model\car\CarOccupyTime;
use app\model\car\CarOrderDepositRefund;
use app\model\car\CarOrderDetail;
use app\model\car\CarOrderRefund;
use app\services\pay\PayServices;
use crmeb\exceptions\AdminException;
use crmeb\services\app\MiniProgramService;
use think\Exception;
use think\facade\Cache;
use app\model\car\CarOrder;
use app\model\car\CarOrderRerent;
use app\model\car\CarOrderReturn;
use app\model\car\CarOrderTake;
use app\model\car\CarType;
use app\model\user\User;
use app\services\BaseServices;
use think\exception\ValidateException;
use think\facade\Db;
use app\services\wechat\WechatUserServices;
use app\services\car\CarTypeServices as carces;


/**
 * Class CarInfoServices
 * @package app\services\shendeng
 */
class CarOrderServices extends BaseServices
{
    public function __construct(CarOrderDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 生成订单唯一id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNewOrderId()
    {
        [$msec, $sec] = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
        if (CarOrder::find(['order_no' => $orderId])) {
            $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
        }
        return $orderId;
    }

    /**
     * 生成订单号 约你游统一规则
     * 2024年1月27日10:41:35
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNewOrderon(){
        $A1 = "A1";
        $ymn  = date('ymd');
        $date = date("His");
        $milliseconds = round(microtime(true) * 1000); // 获取当前时间（单位：毫秒）
        $lastThreeDigits = substr($milliseconds, -3); // 提取最后三位毫秒
        $rand = rand(0000,9999);
        $orderon = $A1.$ymn.$date.$lastThreeDigits.$rand;
        if(CarOrder::find(['order_no' => $orderon])){
            $orderon = $A1.$ymn.$date.$lastThreeDigits.rand(0000,9999);
        }
        return $orderon;
    }



    /**
     * 列表
     * @param array $where
     * @param bool $is_page
     * @param string $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $where = [], bool $is_page = false, string $type = 'user_side')
    {
        $page = $limit = $cancel = 0;
        if ($is_page) [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getList($where, $page, $limit);
        foreach ($list['list'] as &$val) {
            if (empty($val['status'])) {
                if ($val['add_time'] + 1800 < time()) {
                    $this->orderCancel($val['id'], ['user_name' => '系统', 'id' => 0], 4);
                    $cancel++;
                }
            }
        }
        if ($cancel) $this->getList($where, $is_page);
        $status = [0 => ['name' => '未支付', 'color' => '#84C06A'], 10 => ['name' => '待取车', 'color' => '#5580DA'], 20 => ['name' => '待还车', 'color' => '#E5AF0F'], 30 => ['name' => '已还车', 'color' => '#CD5C0A'], 40 => ['name' => '已完成', 'color' => '#84C06A'], -1 => ['name' => '已取消', 'color' => '#CCC9C4']];
        $pay_type = [
            'weixin' => ['color' => 'success', 'name' => '微信支付'],
            'yue' => ['color' => 'warning', 'name' => '余额支付'],
        ];
        foreach ($list['list'] as &$item) {
            $rerent_limit = CarOrderRerent::field('end_time')->where(['order_id' => $item['id'], 'rerent_status' => 20])->order('end_time desc')->find();
            $rerent_limit = $rerent_limit ? $rerent_limit->toArray() : [];
            if ($rerent_limit) {
                $end_time = $rerent_limit['end_time'];
            } else {
                $end_time = $item['end_time'];
            }
            $item['status_cn'] = $status[$item['status']];
            $item['pay_cn'] = $item['pay_time'] > 0 ? $item['pay_type'] ? $pay_type[$item['pay_type']] : ['color' => 'default', 'name' => '未支付'] : ['color' => 'default', 'name' => '未支付'];
            $item['type_gear'] = $item['type_gear'] == 'auto' ? '自动挡' : '手动挡';
            $differ_day = intval(($end_time - $item['start_time']) / 86400);
            $differ_hour = intval(round(($end_time - $item['start_time']) % 86400 / 3600));
            if ($differ_day > 0) {
                if ($differ_hour > 0) {
                    $item['duration'] = $differ_day . '天' . $differ_hour . '小时';
                } else {
                    $item['duration'] = $differ_day . '天';
                }
            } else {
                $item['duration'] = $item['book_hour'] . '小时';
            }
            $item['start_time'] = $item['start_time'] ? date('m-d H:i', $item['start_time']) : '暂无';
            $item['end_time'] = $end_time ? date('m-d H:i', $end_time) : '暂无';
            $item['pay_date'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '暂无';
        }
        return $list;
    }


    /**
     * 列表
     * @param array $where
     * @param bool $is_page
     * @param string $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList2(array $where = [], bool $is_page = false, string $type = 'user_side')
    {
        $page = $limit = $cancel = 0;
        if ($is_page) [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getList($where, $page, $limit);
        foreach ($list['list'] as &$val) {
            if (empty($val['status'])) {
                if ($val['add_time'] + 1800 < time()) {
                    $this->orderCancel($val['id'], ['user_name' => '系统', 'id' => 0], 4);
                    $cancel++;
                }
            }
        }
        if ($cancel) $this->getList($where, $is_page);
        $status = [0 => ['name' => '未支付', 'color' => '#84C06A'], 10 => ['name' => '待取车', 'color' => '#5580DA'], 20 => ['name' => '待还车', 'color' => '#E5AF0F'], 30 => ['name' => '已还车', 'color' => '#CD5C0A'], 40 => ['name' => '已完成', 'color' => '#84C06A'], -1 => ['name' => '已取消', 'color' => '#CCC9C4']];
        $pay_type = [
            'weixin' => ['color' => 'success', 'name' => '微信支付'],
            'yue' => ['color' => 'warning', 'name' => '余额支付'],
        ];
        foreach ($list['list'] as &$item) {
            $rerent_limit = CarOrderRerent::field('end_time')->where(['order_id' => $item['id'], 'rerent_status' => 20])->order('end_time desc')->find();
            $rerent_limit = $rerent_limit ? $rerent_limit->toArray() : [];
            if ($rerent_limit) {
                $end_time = $rerent_limit['end_time'];
            } else {
                $end_time = $item['end_time'];
            }
            $item['status_cn'] = $status[$item['status']];
            $item['pay_cn'] = $item['pay_time'] > 0 ? $item['pay_type'] ? $pay_type[$item['pay_type']] : ['color' => 'default', 'name' => '未支付'] : ['color' => 'default', 'name' => '未支付'];
            $item['type_gear'] = $item['type_gear'] == 'auto' ? '自动挡' : '手动挡';
            $differ_day = intval(($end_time - $item['start_time']) / 86400);
            $differ_hour = intval(round(($end_time - $item['start_time']) % 86400 / 3600));
            if ($differ_day > 0) {
                if ($differ_hour > 0) {
                    $item['duration'] = $differ_day . '天' . $differ_hour . '小时';
                } else {
                    $item['duration'] = $differ_day . '天';
                }
            } else {
                $item['duration'] = $item['book_hour'] . '小时';
            }
            $item['start_time'] = $item['start_time'] ? date('m-d H:i', $item['start_time']) : '暂无';
            $item['end_time'] = $end_time ? date('m-d H:i', $end_time) : '暂无';
            $item['pay_date'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '暂无';
        }
        return $list;
    }


    /**
     * 订单详情
     * @param int $order_id
     * @param string $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderInfo(int $order_id, string $type = 'user_side')
    {
        // 订单信息
        $model = CarOrder::alias('o')->where('o.id', $order_id)
            ->join('car_type t', 't.id=o.type_id', 'left')
            ->join('user u', 'u.uid=o.uid', 'left')
            ->join('car_type_info i', 'i.id=t.type_info_id', 'left')
            ->join('car_category c', 'c.id=i.cate_id', 'left')
            ->join('base_place p1', 'p1.id=o.take_place_id', 'left')
            ->join('base_place p2', 'p2.id=o.return_place_id', 'left')
            ->field('o.*,i.power,i.gear,i.seat_num,c.cate_name,u.nickname,t.deposit,t.illegal_deposit,t.zhoumo_price,t.price as pingri_price,
            p1.poiaddress as take_poiaddress,p1.start_time as take_place_start_time,p1.end_time as take_place_end_time,p1.contact_tel as take_place_contact_tel,
            p2.poiaddress as return_poiaddress,p2.start_time as return_place_start_time,p2.end_time as return_place_end_time,p2.contact_tel as return_place_contact_tel')
            ->find();
        $info = $model ? $model->toArray() : [];
        if (!$info) throw new ValidateException('没有找到订单信息');
        $pay_type = ['weixin' => ['name' => '微信支付', 'color' => 'success'], 'yue' => ['name' => '余额支付', 'color' => 'warning'], 'alipay' => ['name' => '支付宝支付', 'color' => '#1495E7'], 'offline' => ['name' => '线下支付', 'color' => '#D9F5FF']];
        // 驾驶员信息
        $info['contact'] = CarContact::where('id', $info['contact_id'])->find();
        // 下单门店信息
        $info['store_info'] = BasePlace::where('id', $info['store_id'])->find();
        $info['deposit_fee'] = bcadd($info['deposit'], $info['illegal_deposit'], 2);
        // 取车信息
        $take_info = CarOrderTake::alias('t')->where('t.id', $info['take_id'])
            ->join('car_staff s', 's.id=t.take_staff_id', 'left')
            ->field('t.*,s.user_name,s.user_phone')
            ->find();
        $take_info = $take_info ? $take_info->toArray() : [];
        if ($take_info) {
            $take_info['take_time'] = $take_info['take_time'] ? date('Y-m-d H:i:s', $take_info['take_time']) : '暂无';
            $take_info['deposit_pay_time'] = $take_info['deposit_pay_time'] ? date('Y-m-d H:i:s', $take_info['deposit_pay_time']) : '暂无';
            $take_info['deposit_pay_type'] = $pay_type[$take_info['deposit_pay_type']];
            if ($take_info['is_change'] == 1) {
                $take_old = CarType::alias('t')->where('t.id', $take_info['old_type_id'])
                    ->join('car_type_info i', 'i.id=t.type_info_id', 'left')
                    ->field('t.*,i.type_name,i.pic,i.power,i.gear,i.seat_num')
                    ->find();
                $take_info['old_car'] = $take_old ? $take_old->toArray() : [];
                $take_new = CarType::alias('t')->where('t.id', $take_info['new_type_id'])
                    ->join('car_type_info i', 'i.id=t.type_info_id', 'left')
                    ->field('t.*,i.type_name,i.pic,i.power,i.gear,i.seat_num')
                    ->find();
                $take_info['new_car'] = $take_new ? $take_new->toArray() : [];
            }
            $take_info['take_contract_pic'] = json_decode($take_info['take_contract_pic']);
            $take_info['take_injury_pic'] = json_decode($take_info['take_injury_pic']);
        }
        $info['take_info'] = $take_info;
        // 还车信息
        $return_info = CarOrderReturn::alias('r')
            ->where('r.id', $info['return_id'])
            ->join('car_staff s', 's.id=r.return_staff_id', 'left')
            ->field('r.*,s.user_name,s.user_phone')
            ->find();
        $return_info = $return_info ? $return_info->toArray() : [];
//        p(json_decode($return_info['ss_car_array'],JSON_UNESCAPED_UNICODE));exit;

        if ($return_info) {
            $return_info['css_amount'] = Db::name('deposit_record')->where('order_id', $model['id'])->value('css_amount') ?: 0;
            $return_info['is_return'] = $return_info['return_time'] > 0 ? 10 : 0; // 是否还车
            $return_info['return_time'] = $return_info['return_time'] ? date('Y-m-d H:i:s', $return_info['return_time']) : '暂无';
            $return_info['return_injury_item'] = $return_info['return_injury_item'] ? join(',', explode('；', $return_info['return_injury_item'])) : [];
            $return_info['return_injury_pic'] = json_decode($return_info['return_injury_pic']);
            $return_info["ss_car_array"] = json_decode($return_info['ss_car_array'], JSON_UNESCAPED_UNICODE);
        }

        $info['return_info'] = $return_info;
        // 续租订单
        $rerent_info = CarOrderRerent::alias('r')->where(['r.order_id' => $info['id'], 'r.is_del' => 0])
            ->join('car_order o', 'o.id=r.order_id', 'left')
            ->field('r.*,o.contact_name,o.type_name')
            ->order('r.add_time desc')->select()->toArray();
        if ($rerent_info) {
            $rerent_status = [
                -1 => '已取消',
                0 => '未支付',
                10 => '申请续租',
                20 => '同意续租',
                30 => '拒绝续租',
            ];
            foreach ($rerent_info as &$value) {
                $value['add_time'] = $value['add_time'] ? date('Y-m-d H:i:s', $value['add_time']) : '暂无';
                $value['pay_time'] = $value['pay_time'] ? date('Y-m-d H:i:s', $value['pay_time']) : '暂无';
                $value['agree_time'] = $value['agree_time'] ? date('Y-m-d H:i:s', $value['agree_time']) : '暂无';
                $value['refuse_time'] = $value['refuse_time'] ? date('Y-m-d H:i:s', $value['refuse_time']) : '暂无';
                $value['start_time'] = $value['start_time'] ? date('Y-m-d H:i', $value['start_time']) : '暂无';
                $value['end_time'] = $value['end_time'] ? date('Y-m-d H:i', $value['end_time']) : '暂无';
                $value['pay_type'] = $pay_type[$value['pay_type']];
                $value['status'] = $rerent_status[$value['rerent_status']];
            }
        }
        // 退款订单
        $refund = CarOrderRefund::where(['order_id' => $info['id'], 'is_del' => 0, 'order_type' => 1])->order('add_time desc')->find();
        $refund = $refund ? $refund->toArray() : [];
        if ($refund) {
            $refund_status = [
                -5 => '已取消',
                -1 => '已驳回',
                10 => '申请中',
                20 => '已退款',
            ];
            $refund['status_name'] = $refund_status[$refund['status']];
            $refund['add_time'] = date('Y-m-d H:i:s', $refund['add_time']);
        }
        $info['refund_info'] = $refund;
        // 当面收费、扣款
        $detail = CarOrderDetail::where('order_id', $info['id'])->order('add_time desc')->select()->toArray();
        if ($detail) {
            foreach ($detail as &$val) {
                $val['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
            }
        }
        $info['pay_detail'] = $detail;
        $info['rerent_info'] = $rerent_info;
        // 显示处理
        $status = [0 => ['name' => '未支付', 'color' => '#84C06A'], 10 => ['name' => '待取车', 'color' => '#5580DA'], 20 => ['name' => '待还车', 'color' => '#E5AF0F'], 30 => ['name' => '已还车', 'color' => '#CD5C0A'], 40 => ['name' => '已完成', 'color' => '#84C06A'], -1 => ['name' => '已取消', 'color' => '#CCC9C4']];
        $info['status_cn'] = $status[$info['status']];
        $info['pay_type'] = $info['pay_type'] ? $pay_type[$info['pay_type']] : ['name' => '未支付', 'color' => 'default'];
        $info['gear'] = $info['gear'] == 'auto' ? '自动挡' : '手动挡';
        if ($info['is_take_service'] == 1) {
            $info['take_service'] = '商家送车上门';
        } else {
            $info['take_service'] = '自行取车';
        }
        if ($info['is_return_service'] == 1) {
            $info['return_service'] = '商家上门取车';
        } else {
            $info['return_service'] = '自行还车';
        }
        $week = [0 => '周日', 1 => '周一', 2 => '周二', 3 => '周三', 4 => '周四', 5 => '周五', 6 => '周六'];
        // 时间处理
        $start_time = $info['start_time'];
        $rerent_limit = CarOrderRerent::field('end_time')->where(['order_id' => $order_id, 'rerent_status' => 20])->order('end_time desc')->find();
        $rerent_limit = $rerent_limit ? $rerent_limit->toArray() : [];
        if ($rerent_limit) {
            $end_time = $rerent_limit['end_time'];
        } else {
            $end_time = $info['end_time'];
        }
        $info['count_down'] = $info['add_time'] + 60 * 30;
        $info['start_time'] = $info['start_time'] ? date('Y-m-d H:i', $info['start_time']) : '暂无';
        $info['start_month'] = $start_time ? date('m-d', $start_time) : '暂无';
        $info['start_hour'] = $start_time ? date('H:i', $start_time) : '暂无';
        $info['start_week'] = $start_time ? $week[date('w', $start_time)] : '暂无';
        $info['end_time'] = $info['end_time'] ? date('Y-m-d H:i', $info['end_time']) : '暂无';
        $info['end_month'] = $end_time ? date('m-d', $end_time) : '暂无';
        $info['end_hour'] = $end_time ? date('H:i', $end_time) : '暂无';
        $info['end_week'] = $end_time ? $week[date('w', $end_time)] : '暂无';
        $info['pay_time'] = $info['pay_time'] ? date('Y-m-d H:i', $info['pay_time']) : '暂无';
        $info['add_time'] = $info['add_time'] ? date('Y-m-d H:i:s', $info['add_time']) : '暂无';
        $differ_day = intval(($end_time - $start_time) / 86400);
        $differ_hour = intval(round(($end_time - $start_time) % 86400 / 3600));
        if ($differ_day > 0) {
            if ($differ_hour > 0) $info['duration'] = $differ_day . '天' . $differ_hour . '小时';
            else $info['duration'] = $differ_day . '天';
        } else {
            $info['duration'] = $differ_hour . '小时';
        }
        //查询该订单是否有理赔记录
        $get_wz_info = Db::name('car_wz')->where('order_id', $order_id)->count();
        $info["lipei_num"] = $get_wz_info;
        return $info;
    }

    /**
     * 根据日期，获车型租金
     * 每日价>单价
     * @param $type_id
     * @param $date
     * @return mixed
     */
    public function carDatePrice($type_id, $date)
    {
        $care_date_fee = CarDate::where(['type_id' => $type_id, 'book_date' => $date])->value('price'); //获取每日价格
        if ($care_date_fee) {   //存在每日价，使用每日价
            $type_fee = $care_date_fee;
        } else {                //不存在每日价，使用平时价
            $type_fee = CarType::where('id', $type_id)->value('price');
            $check = getWeek($date);
            if ($check == "周日" || $check == "周六") {
                $type_fee = CarType::where('id', $type_id)->value('zhoumo_price');
            }
        }
        return $type_fee;
    }


    /**
     * 小时费计算
     * @param int $type_id
     * @param int $start_time
     * @param int $end_time
     * @return int|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function careHourPrice(int $type_id, int $start_time, int $end_time)
    {
        $hour_time = ($end_time - $start_time) % 86400; //小时数,余数
        $hour_price = 0;
        $care_type = CarType::where(['id' => $type_id, 'is_del' => 0])->find();
        if ($hour_time > 0) {  //存在小时算法
            if ($hour_time < 14400) { //小于4小时
                $hour = ceil($hour_time / 3600); //时间
                $hour_price = bcmul($hour, $care_type['price_hour'], 2);
            } else {   //大于4小时算一天
                $hour_price = $this->carDatePrice($type_id, strtotime(date('Y-m-d', bcsub($end_time, $hour_time, 0))));
                $hour_price = $hour_price/2;
            }
        }
        return $hour_price;
    }


    /**
     * 根据日期段，获取车型租金
     * @param $type_id
     * @param $start_time
     * @param $end_time
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function carFee($type_id, $start_time, $end_time)
    {
        $care_type_fee = 0;
        //整日价格
        while ($start_time <= $end_time) {
            if ($start_time + 86400 > $end_time) { // 不满一天
                break;
            }
            $type_date_price = $this->carDatePrice($type_id, strtotime(date('Y-m-d', $start_time))); //单日价格
            $care_type_fee = bcadd($care_type_fee, $type_date_price, 2);  //单日价格总和
            $start_time += 86400;
        }
        //不足一天价格计算
        $hour_fee = $this->careHourPrice($type_id, $start_time, $end_time);//小时计费
        $price = bcadd($care_type_fee, $hour_fee, 2);//租金总和

        return $price;
    }


    /**
     * 根据日期段，获取车型租金
     * 2024年1月6日11:52:53
     * @param $type_id
     * @param $start_time
     * @param $end_time
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function carFee2($type_id, $start_time, $end_time, $over_hour,$is_yq)
    {
        $care_type_fee = 0;
        $type_date_price = $this->carDatePrice($type_id, strtotime(date('Y-m-d', $end_time))); //单日价格
        $care_type_fee = bcadd($care_type_fee, $type_date_price, 2);  //单日价格总和
        $price = $care_type_fee;//一天价
        if ($is_yq ==2) {
            $price = round(bcmul($care_type_fee, 0.5,3)*100)/100;//1/2价  扣一半
        }

        return $price;
    }

    public function carFee3($type_id, $start_time, $end_time, $over_hour,$is_yq)
    {
        $care_type_fee = 0;
        //整日价格
        while ($start_time <= $end_time) {
            if ($start_time + 86400 > $end_time) { // 不满一天
                break;
            }
            $type_date_price = $this->carDatePrice($type_id, strtotime(date('Y-m-d', $start_time))); //单日价格
            $care_type_fee = bcadd($care_type_fee, $type_date_price, 2);  //单日价格总和
            $start_time += 86400;
        }
        //不足一天价格计算
        $hour_fee = $this->careHourPrice($type_id, $start_time, $end_time);//小时计费
        $price = bcadd($care_type_fee, $hour_fee, 2);//租金总和
        return $price;
    }

    /**
     * 手续费，车辆整备费
     * @param $type_id
     * @return float|mixed
     */
    public function CarTypeServiceFee($type_id)
    {
        $service_cost = Db::name('car_type')->alias('c')
            ->leftJoin('base_place p', 'p.id = c.place_id')
            ->where('c.id', $type_id)
            ->value('p.service_cost');
        return $service_cost ? $service_cost : 0.00;
    }

    /**
     * 根据日期段，获取基础服务费
     * @param $type_id
     * @param $start_time
     * @param $end_time
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function baseServiceFee($type_id, $start_time, $end_time)
    {
        $day = ceil(bcsub($end_time, $start_time) / 86400);  //获取天数,向上舍入
        $care_type = CarType::where(['id' => $type_id, 'is_del' => 0])->find();
        $price = bcmul($day, $care_type['base_service_fee'], 2);
        return $price;
    }

    /**
     * 夜间服务费
     * @param $type_id
     * @param $start_time
     * @param $end_time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function nightFee($type_id, $start_time, $end_time)
    {
        $start_date = date('Y-m-d', $start_time); //开始日期；
        $end_date = date('Y-m-d', $end_time);     //结束日期；
        $place_id = Db::name('car_type')->where('id', $type_id)->value('place_id'); //获取门店信息
        $base_place = BasePlace::where(['id' => $place_id, 'is_del' => 0])->find();
        $price = 0;
        $night_take_fee = 0;   //夜间取车服务费
        $night_return_fee = 0; //夜间还车服务费
        //判断开始时间在不在营业时间内
        if (strtotime($start_date . ' ' . $base_place['start_time']) > $start_time || $start_time > strtotime($start_date . ' ' . $base_place['end_time'])) {
            $price = bcadd($price, $base_place['night_take_fee'], 2);
            $night_take_fee = $base_place['night_take_fee'];
        }
        //判断结束时间在不在营业时间内,还车服务费
        if (strtotime($end_date . ' ' . $base_place['start_time']) > $end_time || $end_time > strtotime($end_date . ' ' . $base_place['end_time'])) {
            $price = bcadd($price, $base_place['night_return_fee'], 2);
            $night_return_fee = $base_place['night_return_fee'];
        }
        return ['night_take_fee' => $night_take_fee, 'night_return_fee' => $night_return_fee, 'price' => $price];
    }

    /**
     * 跨服务点，跨城还车，目前考虑的比较单一（适配单门店）
     * @param $store_id
     * @param $take_place_id
     * @param $return_place_id
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function placeFee($store_id, $take_place_id, $return_place_id)
    {
        if ($take_place_id == $return_place_id) return false;
        $store = BasePlace::where(['id' => $store_id, 'is_del' => 0])->find();                //门店信息
        $take_place = BasePlace::where(['id' => $take_place_id, 'is_del' => 0])->find();      //取车服务点信息
        $return_place = BasePlace::where(['id' => $return_place_id, 'is_del' => 0])->find();  //还车服务点信息
        if ($take_place['city_id'] == $return_place['city_id']) {   //同城，跨服务点
            $long_km = get_distance($take_place['latitude'], $take_place['longitude'], $return_place['latitude'], $return_place['longitude'], 2);
            $price = bcmul($store['place_fee'], $long_km, 2);
            return ['type' => 'place', 'place_long_km' => $long_km, 'price' => $price ? $price : 0.00];
        } else {  //跨城市
            $price = $this->cityFee($take_place['city_id'], $return_place['city_id']);
            return ['type' => 'city', 'place_long_km' => 0, 'price' => $price ? $price : 0.00];
        }
    }

    /**
     * 上门送车，取车费
     * @param $store_id
     * @param $lat
     * @param $lng
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function sendFee($store_id, $lat, $lng)
    {
        $base_place = BasePlace::where(['id' => $store_id])->find();
        if ($base_place['store_id'] > 0) {
            $base_place = BasePlace::where(['id' => $base_place['store_id']])->find();
            $store_id = $base_place['store_id'];
        }
        $long_km = get_distance($base_place['latitude'], $base_place['longitude'], $lat, $lng, 2);
        $base_fee = BaseSendFee::where(['store_id' => $store_id, 'is_del' => 0])->where('mink_km', '<=', $long_km)->where('max_km', '>', $long_km)->find();
        if (!$base_fee) throw new ValidateException('不在配送范围内');
        $base_fee['send_fee'] = $base_fee['send_fee'] ? $base_fee['send_fee'] : 0.00;
        $base_fee['long_km'] = $long_km;
        return $base_fee;
    }

    /**
     * 异地还车费
     * @param $start_city
     * @param $end_city
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cityFee($start_city, $end_city)
    {
        $check = BaseCityFee::where(['start_city_id' => $start_city, 'end_city_id' => $end_city, 'is_del' => 0])->find();
        if (!$check) throw new ValidateException('不符合此异地还车条件');
        return $check['city_fee'];
    }

    /**
     * 获取车辆保险费
     * @param $type_id
     * @param $start_time
     * @param $end_time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getcarService($type_id, $start_time, $end_time)
    {
        $service = Db::name('car_service')->where(['is_del' => 0, 'status' => 1])->field('id,name,price,remark')->select()->toArray();

        $care_type = CarType::where(['id' => $type_id, 'is_del' => 0])->find();
        $day = ceil(bcsub($end_time, $start_time) / 86400);  //获取天数,向上舍入
        $data[] = [
            'id' => 0,
            'name' => '基础服务费',
//            'price' => $this->baseServiceFee($type_id, $start_time, $end_time),
            'price' => $care_type['base_service_fee'],
            'remark' => '保证你的用车体验，店铺工作人员会进行全车清洗，收费150元。',
            'is_select' => false
        ];
        foreach ($service as $v) {
            $data[] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'price' => bcmul($v['price'], $day, 2),
                'remark' => $v['remark'],
                'unit_price' => $v['price'],
                'day' => $day,
                'is_select' => false
            ];
        }
        return $data;
    }

    /**
     * 获取已领取优惠券列表
     * @param $uid
     * @param $price
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_use_coupon($uid, $price)
    {
        $result = [];
        $userCoupons = (new StoreCouponUserDao())->getUserAllCoupon($uid);
        if ($userCoupons) {
            foreach ($userCoupons as $coupon) {
                //限制优惠券金额不能大于订单金额
                if ($coupon['use_min_price'] <= $price) {
                    $coupon['start_time'] = $coupon['start_time'] ? date('Y/m/d', $coupon['start_time']) : date('Y/m/d', $coupon['add_time']);
                    $coupon['add_time'] = date('Y/m/d', $coupon['add_time']);
                    $coupon['end_time'] = date('Y/m/d', $coupon['end_time']);
                    $coupon['title'] = $coupon['coupon_title'];
                    $coupon['type'] = $coupon['applicable_type'];
                    $coupon['use_min_price'] = floatval($coupon['use_min_price']);
                    $coupon['coupon_price'] = floatval($coupon['coupon_price']);
                    $result[] = $coupon;
                }
            }
        }
        return $result;
    }

    /**
     * 获取tab数据
     * @param array $where
     * @return array
     */
    public function getTabsData(array $where = [])
    {
        $data['all'] = (string)$this->dao->getOrderCount($where + ['status' => 'all']);
        $data['status0'] = (string)$this->dao->getOrderCount($where + ['status' => 0]);
        $data['status10'] = (string)$this->dao->getOrderCount($where + ['status' => 10]);
        $data['status20'] = (string)$this->dao->getOrderCount($where + ['status' => 20]);
        $data['status30'] = (string)$this->dao->getOrderCount($where + ['status' => 30]);
        $data['status40'] = (string)$this->dao->getOrderCount($where + ['status' => 40]);
        $data['status_1'] = (string)$this->dao->getOrderCount($where + ['status' => -1]);
        return $data;
    }

    /**
     * 订单日志
     * @param int $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderLog(int $order_id)
    {
        /** @var BaseLogServices $log_services */
        $log_services = app(BaseLogServices::class);
        $list = $log_services->getLog($order_id, 2);
        return $list;
    }

    /**
     * 订单流水
     * @param int $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderFlow(int $order_id)
    {
        /** @var BaseLogServices $log_services */
        $log_services = app(BaseLogServices::class);
        $list = $log_services->getFlow($order_id, 2);
        return $list;
    }

    /**
     * 订单备注
     * @param $data
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderRemark($data)
    {
        $order = CarOrder::where('id', $data['order_id'])->find();
        $order->remark = $data['remark'];
        if (!$order->save()) throw new ValidateException('备注失败');
        return '备注成功';
    }

    /**
     * 车辆租金固定费用
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCareFee($where)
    {
        $car_fee = $this->carFee($where['type_id'], $where['start_time'], $where['end_time']);//车辆纯租金费
        $service_cost = $this->CarTypeServiceFee($where['type_id']);//手续费、车辆整备费
        $price = bcadd($car_fee, $service_cost, 2);
        //夜间服务费
        $night = $this->nightFee($where['type_id'], $where['start_time'], $where['end_time']);
        $night_take_fee = $night['night_take_fee']; //取车夜间费
        $night_return_fee = $night['night_return_fee']; //还车夜间费
        $night_all_price = $night['price'];   //夜间总费
        $price = bcadd($night['price'], $price, 2);
        //异店还车费
        $other_places_fee = 0;
        $place_fee = 0; //跨服务点
        $city_fee = 0;  //跨城
        $place_long_km = 0; //还车公里
        if ($where['is_other_places'] && !$where['is_visit']) {
            $other_places = $this->placeFee($where['store_id'], $where['take_place_id'], $where['return_place_id']);
            $other_places_fee = $other_places['price'];
            $place_fee = $other_places['type'] == 'place' ? $other_places['price'] : 0.00;
            $city_fee = $other_places['type'] == 'city' ? $other_places['price'] : 0.00;
            $place_long_km = $other_places['place_long_km'];
            $price = bcadd($other_places_fee, $price, 2);
        }
        //上门送取车
        $take_visit_fee = 0;  //上门取车费
        $take_long_km = 0;    //上门公里数
        $return_visit_fee = 0; //上门还车费
        $return_long_km = 0;   //上门还车公里
        $visit = 0;            //总费用
        if ($where['is_visit']) {
            if (!$where['take_place_id']) {
                $take_visit = $this->sendFee($where['store_id'], $where['take_latitude'], $where['take_longitude']);
                $take_visit_fee = $take_visit['send_fee'];
                $take_long_km = $take_visit['long_km'];
                $price = bcadd($take_visit_fee, $price, 2);
            }
            if (!$where['return_place_id']) {
                $return_visit = $this->sendFee($where['store_id'], $where['return_latitude'], $where['return_longitude']);
                $return_visit_fee = $return_visit['send_fee'];
                $return_long_km = $return_visit['long_km'];
                $price = bcadd($return_visit_fee, $price, 2);
            }
            $visit = bcadd($take_visit_fee, $return_visit_fee, 2);
            //都在服务点，但点不同
            if ($where['take_place_id'] && $where['return_place_id'] && ($where['take_place_id'] !== $where['return_place_id'])) {
                $other_places = $this->placeFee($where['store_id'], $where['take_place_id'], $where['return_place_id']);
                $other_places_fee = $other_places['price'];
                $place_fee = $other_places['type'] == 'place' ? $other_places['price'] : 0.00;
                $city_fee = $other_places['type'] == 'city' ? $other_places['price'] : 0.00;
                $place_long_km = $other_places['place_long_km'];
                $price = bcadd($other_places_fee, $price, 2);
            }
        }
        //获取车辆信息
        $CarTypeService = app()->make(CarTypeServices::class);
        $car_info = $CarTypeService->getCarInfo(['car_type_id' => $where['type_id']]);
        //租金+车辆押金+违章押金
        $deposit = $car_info['deposit'] + $car_info['illegal_deposit'];
        $price = bcadd($price, $deposit, 2);
        //总费用
        $original_price = $price;
        $result = compact(
            'car_fee',
            'other_places_fee',
            'service_cost',
            'night_take_fee',
            'night_return_fee',
            'night_all_price',
            'price',
            'original_price',
            'take_visit_fee',
            'return_visit_fee',
            'visit',
            'place_fee',
            'place_long_km',
            'city_fee',
            'take_long_km',
            'return_long_km'
        );
        $result['base_service_fee'] = $car_info['base_service_fee'];//基础服务费
        $result['price_hour'] = $car_info['price_hour'];//小时费用
        $result['deposit'] = $car_info['deposit'];//车辆押金
        $result['illegal_deposit'] = $car_info['illegal_deposit'];//违章押金
        $result['zhoumo_price'] = $car_info['zhoumo_price'];//周末价格
        $result['pr_price'] = $car_info['price'];//周末价格
        return $result;
    }

    /**
     * 创建订单
     * @param $data
     * @param $op_user
     * @param $op_user_type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createOrder($data, $op_user, $op_user_type)
    {
        $contact = CarContact::find(['id' => $data['contact_id']]);
        /** @var CarBlacklistServices $carBlacklistServices */
        $carBlacklistServices = app()->make(CarBlacklistServices::class);
        $carBlacklistServices->verifyBlacklist(['phone' => $contact['phone'], 'card_id' => $contact['card_no']]);
        $fee = $this->getCareFee($data);  //获取基础车辆租金
        $car_time = get_hire_day($data['start_time'], $data['end_time']);
        $price = $fee['price'];
        $car_fee = $fee['car_fee'];
        $yajin = $fee['deposit'] + $fee['illegal_deposit'];
        $ffw = $fee['base_service_fee'];
        $CarTypeService = app()->make(CarTypeServices::class);
        $car_type = $CarTypeService->getCarInfo(['car_type_id' => $data['type_id']]);
        $mchid = Db::name('base_place')->where('id', $data['store_id'])->value('sub_mchid');

        $update = [
            'uid' => $data['uid'],
            'type_id' => $data['type_id'],
            'type_name' => $car_type['type_name'],
            'type_pic' => $car_type['pic'],
            'type_price' => $car_type['price'],
            'car_price' => $car_type['price'],
            'car_price_hour' => $car_type['price_hour'],
            'order_no' => $this->getNewOrderon(),
            'contact_id' => $data['contact_id'],
            'contact_name' => $contact['name'],
            'contact_mobile' => $contact['phone'],
            'take_city_id' => $data['take_city_id'],
            'return_city_id' => $data['return_city_id'],
            'store_id' => $data['store_id'],
            'is_take_service' => $data['is_visit'] ? 1 : 0,
            'take_place_id' => $data['take_place_id'],
            'take_title' => $data['take_title'],
            'take_latitude' => $data['take_latitude'],
            'take_longitude' => $data['take_longitude'],
            'home_take_km' => $fee['take_long_km'],
            'home_take_price' => $fee['take_visit_fee'],
            'is_return_service' => $data['is_visit'] ? 1 : 0,
            'return_place_id' => $data['return_place_id'],
            'return_title' => $data['is_visit'] ? $data['return_title'] : $data['take_title'],
            'return_latitude' => $data['is_visit'] ? $data['return_latitude'] : $data['take_latitude'],
            'return_longitude' => $data['is_visit'] ? $data['return_longitude'] : $data['take_longitude'],
            'home_return_km' => $fee['return_long_km'],
            'home_return_price' => $fee['return_visit_fee'],
            'start_time' => $data['start_time'],
            'end_time' => $data['end_time'],
            'book_day' => $car_time['day'],
            'book_hour' => $car_time['hour'],
            'car_fee' => $fee['car_fee'],
            'service_cost' => $fee['service_cost'],
            'night_take_fee' => $fee['night_take_fee'],
            'night_return_fee' => $fee['night_return_fee'],
            'place_fee' => $fee['place_fee'],
            'place_km' => $fee['place_long_km'],
            'city_fee' => $fee['city_fee'],
            'old_price' => $price,
            'coupon_user_id' => $data['coupon_user_id'],
            'coupon_price' => $data['coupon_price'],
            'status' => 0,
            'add_time' => time(),
            'deposit' => $car_type['deposit'],
            'illegal_deposit' => $car_type['illegal_deposit'],
            'mchid' => $mchid,
            'yajin' => $car_type['deposit'] + $car_type['illegal_deposit'],
            'shifu_car_fee' => $car_fee,
            'car_id' =>$data['car_id'],//车辆id
            'car_no' =>$data['car_no']//车牌号
        ];
        //查询车子是否被占用，查询该车型下面是否有车辆可租
        $carInfoServices = app()->make(CarInfoServices::class);
        $carInfoServices->getCarInventory2($update['type_id'],$update['start_time'],$update['end_time'],$update['car_id']);
        $check_car_service = 2;
        foreach ($data['car_service'] as $v) {
            if ($v['is_select'] == true) {
                $check_car_service = 1;
                $price = bcadd($price, $v['price'], 2);
                if ($v['id'] == 0) {
                    $update['base_service_fee'] = $v['price'];
                } else {
                    $update['car_service_id'] = $v['id'];
                    $update['car_service_name'] = $v['name'];
                    $update['car_service_price'] = $v['price'];
                    $update['car_service_fee'] = $v['price'];
                }
            }
        }
        $update['old_price'] = $price;
        $update['price'] = $price;
        if ($data['coupon_user_id'] > 0) {
            $coupon = Db::name('store_coupon_user')->where('id', $data['coupon_user_id'])->where(['is_fail' => 0, 'status' => 0])->find();
            if (!$coupon) throw new ValidateException('获取优惠券失败');
            $you = bcsub($car_fee, $coupon['coupon_price'], 2);
            if ($you <= 0) $you = 0;
            $update['shifu_car_fee'] = $you;
            if ($check_car_service == 1) $you = bcadd($you, $ffw, 2);
//            $update['price'] = bcsub($update['price'], $coupon['coupon_price'], 2);
            $update['price'] = bcadd($you, $yajin, 2);
            $update['coupon_user_id'] = $coupon['id'];
            $update['coupon_price'] = $coupon['coupon_price'];
            Db::name('store_coupon_user')->where(['id' => $coupon['id']])->update(['status' => 1]); //使用优惠券
        }
//        if($update['price'] <= 0.01) $update['price'] = 0.01;
        $insert = Db::name('car_order')->insertGetId($update);
        if (!$insert) throw new ValidateException('提交订单失败');
        $title = '订单创建成功';
        BaseLogServices::addLog($insert, 2, $title, $op_user_type, $op_user['uid'], $op_user['nickname'], 1);
        return ['order_id' => $insert];
    }

    /**
     * 订单支付
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payOrder($data)
    {
        $order = CarOrder::where('id', $data['order_id'])->find();
        $user = User::where('uid', $data['uid'])->find();
        if ($order['pay_time'] > 0) throw new ValidateException('订单已支付，不可重复支付');
        switch ($data['pay_type']) {
            case 'yue':
                if ($user['now_money'] < $order['price']) throw new ValidateException('当前余额不足，请及时充值');
                $yueServices = app()->make(OrderPayServices::class);
                $pay = $yueServices->yueCarOrderPay($order, $data['uid'], $user, 1);
                if ($pay['status'] === true) return true;
                else {
                    if (is_array($pay)) {
                        throw new ValidateException($pay['msg']);
                    } else {
                        throw new ValidateException($pay);
                    }
                }
                break;
            case 'Offline':
                break;
            case 'weixin':
                if ($order['price'] <= 0) {
                    throw new ValidateException('支付订单金额不能小于或等于0');
                } else {
                    $payServices = app()->make(OrderPayServices::class);
                    $from = 'routine';
                    $jsConfig = $payServices->orderPay($order, $from, $user, 1);
                    return $jsConfig;
                }
                break;
        }
    }

    /**
     * 费用明细
     * @param int $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderCost(int $order_id)
    {
        $price = ['price' => 0.00];
        $orderInfo = CarOrder::where('id', $order_id)->find();
        $orderInfo = $orderInfo ? $orderInfo->toArray() : [];
        // 订单费用明细
        $price['order'] = $this->orderCost($orderInfo['id']);
        $price['price'] = bcadd($price['price'], $price['order']['price'], 2);
        // 续租订单费用明细
        $price['rerent'] = $this->rerentCost($orderInfo['id']);
        $price['price'] = bcadd($price['price'], $price['rerent']['price'], 2);
        // 取车费用明细
        $price['take'] = $this->takeCost($orderInfo['take_id']);
        $price['price'] = bcadd($price['price'], $price['take']['price'], 2);
        // 其他费用明细
        $price['rests'] = $this->restsCost($orderInfo['id']);
        if ($price['rests']) $price['price'] = bcadd($price['price'], $price['rests']['price'], 2);
        return $price;
    }

    /**
     * 订单费用明细
     * @param $order_id
     * @return array|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderCost($order_id)
    {
        $order = CarOrder::find($order_id);
        $order = $order ? $order->toArray() : [];
        if (!$order) return $order;
        $price['home_take_price'] = $order['home_take_price'];
        $price['home_return_price'] = $order['home_return_price'];
        $price['car_fee'] = $order['car_fee'];
        $price['base_service_fee'] = $order['base_service_fee'];
        $price['service_cost'] = $order['service_cost'];
        $price['car_service_fee'] = $order['car_service_fee'];
        $price['night_take_fee'] = $order['night_take_fee'];
        $price['night_return_fee'] = $order['night_return_fee'];
        $price['place_fee'] = $order['place_fee'];
        $price['city_fee'] = $order['city_fee'];
        $price['coupon_price'] = $order['coupon_price'];
        $price['integral_price'] = $order['integral_price'];
        $price['illegal_deposit'] = $order['illegal_deposit'];
        $price['deposit'] = $order['deposit'];
        $price['price'] = $order['price'];
        return $price;
    }

    /**
     * 续租订单费用明细
     * @param $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function rerentCost($order_id)
    {
        $rerent = CarOrderRerent::where(['order_id' => $order_id, 'is_del' => 0])->where('rerent_status', '>', -1)->select()->toArray();
        $price = ['price' => 0, 'rerent' => []];
        if (!$rerent) return $price;
        foreach ($rerent as $item) {
            $temp['car_fee'] = $item['car_fee'];
            $temp['base_service_fee'] = $item['base_service_fee'];
            $temp['car_service_fee'] = $item['car_service_fee'];
            $temp['price'] = $item['rerent_price'];
            $temp['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
            $temp['is_pay'] = $item['pay_time'] ? '已支付' : '未支付';
            $price['price'] = bcadd($price['price'], $item['rerent_price'], 2);
            $price['rerent'][] = $temp;
        }
        return $price;
    }

    /**
     * 取车费用明细
     * @param $take_id
     * @return int[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function takeCost($take_id)
    {
        $take = CarOrderTake::find($take_id);
        $price = ['price' => 0];
        $take = $take ? $take->toArray() : [];
        if (!$take) return $price;
        $price['illegal_deposit'] = $take['illegal_deposit'];
        $price['deposit'] = $take['deposit'];
        $price['all_deposit_fee'] = $take['all_deposit_fee'];
        $price['integral_fee'] = $take['integral_fee'];
        $price['price'] = $take['deposit_fee'];
        $price['deposit_is_pay'] = $take['deposit_is_pay'];
        return $price;
    }

    /**
     * 还车费用明细
     * @param $return_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function returnCost($return_id)
    {
        $return = CarOrderReturn::find($return_id);
        $return = $return ? $return->toArray() : [];
        if (!$return) return [];
        return $return;
    }

    /**
     * 收费与扣费明细
     * @param $order_id
     * @return array|int[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function restsCost($order_id)
    {
        $rests = CarOrderDetail::where('order_id', '=', $order_id)->select()->toArray();
        if (!$rests) return [];
        $price = ['price' => 0];
        foreach ($rests as $val) {
            $price['price'] = bcadd($price['price'], $val['price']);
        }
        $price['rests'] = $rests;
        return $price;
    }

    /**
     * 取消订单
     * @param int $order_id
     * @param array $op_user
     * @param int $op_user_type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderCancel(int $order_id, array $op_user, int $op_user_type)
    {
        $orderInfo = CarOrder::where('id', $order_id)->find();
        $orderInfo = $orderInfo ? $orderInfo->toArray() : [];
        if (!$orderInfo) throw new ValidateException('未查询到订单信息');
        // 判断用户取消时间是否在取消规则内
        if (empty($orderInfo['pay_time'])) {
            Db::startTrans();
            try {
                $res1 = Db::name('car_order')->where('id', $order_id)->update(['status' => -1, 'cancel_time' => time()]);
                $res2 = Db::name('car_occupy_time')->where('order_id', $order_id)->update(['is_del' => 1, 'delete_time' => time()]);
                if ($orderInfo['coupon_user_id'] > 0) {
                    //退还优惠券
                    Db::name('store_coupon_user')->where('id', $orderInfo['coupon_user_id'])->update(['status' => 0]);
                }
                $title = $op_user['user_name'] . '取消订单（未支付）';
                BaseLogServices::addLog($orderInfo['id'], 2, $title, $op_user_type, $op_user['id'], $op_user['user_name'], 2);
                Db::commit();
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['msg' => '处理失败，' . $e->getMessage(), 'status' => 400];
            }
            return ['type' => 0, 'msg' => '取消成功'];
        }
        $return = CarOrderRefund::where(['order_id' => $orderInfo['id'], 'is_del' => 0, 'status' => 10])->find();
        $return = $return ? $return->toArray() : [];
        if ($return) throw new ValidateException('订单已提交过取消申请，无需重复提交');
        if($orderInfo['status']==20)throw new ValidateException('订单已取车，无法取消订单！');
        if($orderInfo['status']==30)throw new ValidateException('订单已还车，无法取消订单！');
        if($orderInfo['status']==40)throw new ValidateException('订单已完成，无法取消订单！');
        Db::startTrans();
        try {
            //已支付待取车才可取消
            $time = time();
            $wyj = 1;
            if ($orderInfo['start_time'] > $time + 86400) {  //24小时前
                $title = $op_user['user_name'] . '取消订单并提交退款申请';
            } else if ($orderInfo['start_time'] >= $time + 43200 && $orderInfo['start_time'] <= $time + 86400) {//距离取车时间24小时以内---12小时(含)10%作为违约金
                $wyj = 0.1;
                $title = $op_user['user_name'] . '取消订单并提交退款申请,距离取车时间24小时以内---12小时(含) 扣除（车辆租赁及服务费）10%作为违约金';
            } elseif ($orderInfo['start_time'] >= $time + 18000 && $orderInfo['start_time'] <= $time + 43200) {//距离取车时12小时内---5小时(含) 20%作为违约金
                $wyj = 0.2;
                $title = $op_user['user_name'] . '取消订单并提交退款申请,距离取车时12小时内---5小时(含) 扣除（车辆租赁及服务费）20%作为违约金';
            } elseif ($time + 18000 >= $orderInfo['start_time']) {//距离取车时间不足5小时 30%作为违约金
                $wyj = 0.3;
                $title = $op_user['user_name'] . '取消订单并提交退款申请,距离取车时间不足5小时 扣除（车辆租赁及服务费）30%作为违约金';
            }

            //实付租车费+服务费
            $car_fee = $orderInfo['shifu_car_fee'] + $orderInfo['base_service_fee'];
            $car_fee_a = bcmul($car_fee, $wyj, 2);//需要扣除的钱
            if ($wyj == 1) $car_fee_a = 0;
            $car_fee_t = bcsub($car_fee, $car_fee_a, 2);//退的钱
            $car_fee_t = bcadd($car_fee_t, $orderInfo['yajin'], 2);//退的钱+押金
            $order_refund = [
                'order_id' => $orderInfo['id'],
                'uid' => $orderInfo['uid'],
                'refund_no' => $this->getNewOrderSn('r'),
                'price' => $car_fee_t,
                'add_time' => time(),
                'order_type' => 1,
                'deduct_price' => $car_fee_a,
                'yuan_price' => $car_fee,
                'remark' => $title,
                'tui_price_time'=>time()+86400
            ];
            $order_refund['status'] = 10;
            $refund_id = Db::name('car_order_refund')->insertGetId($order_refund);
            /** @var CarOrderRefundServices $refundServices */
            $refundServices = app()->make(CarOrderRefundServices::class);
            $refundData = Db::name('car_order_refund')->find(['id' => $refund_id]);
            $res2 = Db::name('car_occupy_time')->where('order_id', $order_id)->update(['is_del' => 1, 'delete_time' => time()]);
            if ($orderInfo['coupon_user_id'] > 0) {
                //退还优惠券
                Db::name('store_coupon_user')->where('id', $orderInfo['coupon_user_id'])->update(['status' => 0]);
            }
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['msg' => '处理失败，' . $e->getMessage(), 'status' => 400];
        }

//        $refundServices->payOrderRefund($orderInfo, $refundData);  //直接退款
        BaseLogServices::addLog($orderInfo['id'], 2, $title, $op_user_type, $op_user['id'], $op_user['user_name'], 2);
        return ['type'=>1,'msg'=>'取消申请已提交'];
//        return ['type' => 0, 'msg' => '取消成功'];
//        else{
//            $title = $op_user['user_name'].'取消订单（已支付）';
//            BaseLogServices::addLog($orderInfo['id'],2,$title,$op_user_type,$op_user['id'],$op_user['user_name'],2);
//            return ['type'=>1,'msg'=>'取消申请已提交'];
//        }
    }

    /**
     * 订单导出
     * @param $where
     * @return mixed
     */
    public function getExportData($where)
    {
        $list = $this->dao->exportOrder($where);
        foreach ($list as &$item) {
            $item['add_time'] = $item['add_time'] ? date('Y年m月d日 H时i分', $item['add_time']) : '暂无';
            $item['pay_status'] = $item['pay_time'] ? '已支付' : '未支付';
            $item['start_time'] = $item['start_time'] ? date('m月d日 H时i分', $item['start_time']) : '暂无';
            $item['end_time'] = $item['end_time'] ? date('m月d日 H时i分', $item['end_time']) : '暂无';
            $item['time'] = $item['start_time'] . '至' . $item['end_time'];
            $item['pay_time'] = $item['pay_time'] ? date('Y年m月d日 H时i分s秒', $item['pay_time']) : '暂无';
        }
        return $list;
    }

    /**
     * 订单导出超明细
     * 2024年3月11日16:49:03
     * @param $where
     * @return mixed
     */
    public function getExportData2($where){

        // 关键字
        if(isset($where['keyword']) && $where['keyword']){
            if($where['field_key'] == 'all'){
                $where2[] = ['o.order_no|o.contact_name|o.contact_mobile','like',"%{$where['keyword']}%"];
            }elseif($where['field_key'] == 'order_no'){
                $where2[] = ['o.order_no','like',"%{$where['keyword']}%"];
            }elseif($where['field_key'] == 'name'){
                $where2[] = ['o.contact_name','like',"%{$where['keyword']}%"];
            }elseif($where['field_key'] == 'phone'){
                $where2[] = ['o.contact_mobile','like',"%{$where['keyword']}%"];
            }
        }
        if(!empty($where['start_time']) && !empty($where['end_time']) ){
            $where2[] = ["o.add_time",">=",$where['start_time']];
            $where2[] = ["o.add_time","<=",$where['end_time']];
        }
        $where2[] = ['o.pay_time','<>',''];
        $data = Db::name('car_order')
            ->alias('o')
            ->field('o.id,o.order_no,o.contact_name,o.contact_mobile,u.account,t.car_no,o.type_name,p.title as store_name,from_unixtime(o.pay_time)pay_time,o.out_trade_no,
            o.status,o.book_day,from_unixtime(o.start_time)start_time,from_unixtime(o.end_time)end_time,from_unixtime(t.add_time)qc_time,from_unixtime(r.add_time)hc_time,
            o.book_day as shiji_day,o.car_price,o.base_service_fee,o.deposit,o.illegal_deposit,c.coupon_title,c.coupon_title,c.coupon_price,o.old_price,o.price,from_unixtime(o.cancel_time)cancel_time,o.cancel_refund_price,
            r.tui_car_fee_time,r.tui_wz_fee_time')
            ->join('user u','u.uid = o.uid','left')
            ->join('car_order_take t','t.id=o.take_id','left')
            ->join('car_order_return r','r.id=o.return_id','left')
            ->join('base_place p','p.id=o.store_id','left')
            ->join('store_coupon_user c','c.id=o.coupon_user_id','left')
            ->where($where2)
            ->select()->toArray();

        $time = time();
        foreach ($data as $k=>$v) {
            if($v['status']==-1){
                $data[$k]['status'] = "已取消";
            }elseif($v["status"]==0){
                $data[$k]['status'] = "未支付";
            }elseif($v["status"]==10){
                $data[$k]['status'] = "待取车";
            }elseif($v["status"]==20){
                $data[$k]['status'] = "租赁中";
            }elseif($v["status"]==30){
                $data[$k]['status'] = "已还车";
            }elseif($v["status"]==40){
                $data[$k]['status'] = "已完成";
            }
            $data[$k]['car_yajin_t'] = 0;
            $data[$k]['car_yajin_k'] = 0;
            $data[$k]['car_yajin_time'] = "";
            $data[$k]['wz_yajin_t'] = 0;
            $data[$k]['wz_yajin_k'] = 0;
            $data[$k]['wz_yajin_time'] = "";

            $data[$k]['koufei_mingxi'] = "";//扣费明细
            if($v['tui_car_fee_time']<$time){
                $car = Db::name('deposit_record')->where(['type'=>1,'order_id'=>$v['id']])->find();
                if($car){
                    $data[$k]['car_yajin_t'] = $car['t_amount'];
                    $data[$k]['car_yajin_k'] = $car['k_amount'];
                    $data[$k]['car_yajin_time'] = date('Y年m月d日 H时i分s秒', $car['add_time']);
                    if($car['k_amount']>0){
                        $data[$k]['koufei_mingxi'] = "车损扣费：".$car['k_amount']."元";
                    }

                }
            }
            if($v['tui_wz_fee_time']<$time){
                $wz = Db::name('deposit_record')->where(['type'=>2,'order_id'=>$v['id']])->find();
                if($wz){
                    $data[$k]['wz_yajin_t'] = $wz['t_amount'];
                    $data[$k]['wz_yajin_k'] = $wz['k_amount'];
                    $data[$k]['wz_yajin_time'] = date('Y年m月d日 H时i分s秒', $wz['add_time']);
                    if($wz['k_amount']>0){
                        $data[$k]['koufei_mingxi']= $data[$k]['koufei_mingxi']."违章扣费：".$wz['k_amount']."元";
                    }
                }
            }
        }
        return $data;
//        p(Db::getLastSql());exit;
    }


    /**
     * 使用雪花算法生成订单ID
     * @return string
     * @throws \Exception
     */
    public function getNewOrderSn(string $prefix = 'p')
    {
        $snowflake = new \Godruoyi\Snowflake\Snowflake();
        $is_callable = function ($currentTime) {
            $redis = Cache::store('redis');
            $swooleSequenceResolver = new \Godruoyi\Snowflake\RedisSequenceResolver($redis->handler());
            return $swooleSequenceResolver->sequence($currentTime);
        };
        //32位
        if (PHP_INT_SIZE == 4) {
            $id = abs($snowflake->setSequenceResolver($is_callable)->id());
        } else {
            $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->setSequenceResolver($is_callable)->id();
        }
        return $prefix . $id;
    }

    /**
     * 获取特定时间内订单量
     * @param $time
     * @return int
     */
    public function todayOrderVisit($time)
    {
        return CarOrder::where('pay_time', '>', 0)->where(['is_del' => 0, 'status' => 40])->whereTime('add_time', $time)->count();
    }

    /**
     * 获取一段时间内订单列表
     * @param $datebefor
     * @param $dateafter
     * @param string $timeType
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderAddTimeList($datebefor, $dateafter, $timeType = "week")
    {
        return CarOrder::where('add_time', 'between time', [$datebefor, $dateafter])->where('is_del', 0)->where('status', 40)
            ->when($timeType, function ($query) use ($timeType) {
                $timeUnix = "%w";
                switch ($timeType) {
                    case "week" :
                        $timeUnix = "%w";
                        break;
                    case "month" :
                        $timeUnix = "%d";
                        break;
                    case "year" :
                        $timeUnix = "%m";
                        break;
                    case "30" :
                        $timeUnix = "%m-%d";
                        break;
                }
                $query->field("FROM_UNIXTIME(add_time,'$timeUnix') as day,count(*) as count,sum(price) as price");
                $query->group("FROM_UNIXTIME(add_time, '$timeUnix')");
            })
            ->order('add_time asc')
            ->select()->toArray();
    }

    /**
     * 统计总数上期
     * @param $pre_datebefor
     * @param $pre_dateafter
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function preTotalFind($pre_datebefor, $pre_dateafter)
    {
        return CarOrder::where('add_time', 'between time', [$pre_datebefor, $pre_dateafter])->where('is_del', 0)->where('status', 40)
            ->field("count(*) as count,sum(price) as price")
            ->find();
    }

    /**
     * 获取一段时间内订单列表
     * @param $now_datebefor
     * @param $now_dateafter
     * @param string $timeType
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function nowOrderList($now_datebefor, $now_dateafter, $timeType = "week")
    {
        return CarOrder::where('add_time', 'between time', [$now_datebefor, $now_dateafter])->where('is_del', 0)->where('status', 40)
            ->when($timeType, function ($query) use ($timeType) {
                $timeUnix = "%w";
                switch ($timeType) {
                    case "week" :
                        $timeUnix = "%w";
                        break;
                    case "month" :
                        $timeUnix = "%d";
                        break;
                    case "year" :
                        $timeUnix = "%m";
                        break;
                }
                $query->field("FROM_UNIXTIME(add_time,'$timeUnix') as day,count(*) as count,sum(price) as price");
                $query->group("FROM_UNIXTIME(add_time, '$timeUnix')");
            })
            ->order('add_time asc')
            ->select()->toArray();
    }

    /**
     * 完成订单
     * @param int $order_id
     * @param array $op_user
     * @param int $op_user_type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderClosing(int $order_id, array $op_user, int $op_user_type)
    {
        $orderInfo = CarOrder::find($order_id);
        $orderInfo = $orderInfo ? $orderInfo->toArray() : [];
        if (!$orderInfo) throw new AdminException('未查询到订单信息');
        $this->transaction(function () use ($orderInfo, $op_user, $op_user_type) {
            if (CarOrder::where(['id' => $orderInfo['id']])->update(['status' => 40])) {
                $title = '订单【' . $orderInfo['order_no'] . '】完成结算';
                $commission_service = app()->make(CommissionServices::class);
                $user = Db::name('user')->where('uid', $orderInfo['uid'])->find();
                $res2 = $commission_service->backOrderBrokerage($orderInfo, $user);
                BaseLogServices::addLog($orderInfo['id'], 2, $title, $op_user_type, $op_user['id'], $op_user['user_name'], 17);
                return true;
            } else {
                throw new AdminException('提交失败');
            }
        });
        return '提交成功';
    }

    /**
     * 获取退款订单
     * @param int $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderRefund(int $order_id)
    {
        $refund = CarOrderRefund::where(['order_id' => $order_id, 'is_del' => 0, 'order_type' => 1])->where('status', 'in', '10,20')->find();
        $refund = $refund ? $refund->toArray() : [];
        if (!$refund) return [];
        $status = [
            -5 => '已取消',
            -1 => '已驳回',
            10 => '申请中',
            20 => '已退款',
        ];
        $refund['status_name'] = $status[$refund['status']];
        $refund['add_time'] = $refund['add_time'] ? date('Y-m-d H:i:s', $refund['add_time']) : '暂无';
        return $refund;
    }

    /**
     * 获取续租退款订单
     * @param int $rerent_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRerentRefund(int $rerent_id)
    {
        $refund = CarOrderRefund::where(['order_id' => $rerent_id, 'is_del' => 0, 'order_type' => 2])->where('status', 'in', '10,20')->find();
        $refund = $refund ? $refund->toArray() : [];
        if (!$refund) return [];
        $status = [
            -5 => '已取消',
            -1 => '已驳回',
            10 => '申请中',
            20 => '已退款',
        ];
        $refund['status_name'] = $status[$refund['status']];
        $refund['add_time'] = $refund['add_time'] ? date('Y-m-d H:i:s', $refund['add_time']) : '暂无';
        return $refund;
    }

    /**
     * 超半小时未支付自动取消订单
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function systemCancelOrder()
    {
        $order = CarOrder::field('id,order_no,add_time')->where(['is_del' => 0, 'status' => 0])->where('add_time', '<', time() - 1800)->select()->toArray();
        $success = 0;
        $error = 0;
        foreach ($order as $item) {
            if (CarOrder::where('id', $item['id'])->update(['status' => -1, 'cancel_time' => time()])) {
                BaseLogServices::addLog($item['id'], 2, '超时未支付，系统取消订单', 4, 0, '系统', 2);
                CarOccupyTime::where('order_id', $item['id'])->update(['is_del' => 1, 'delete_time' => time()]);
                $success++;
            } else {
                $error++;
            }
        }
        return '执行成功' . $success . '条，失败' . $error . '条';
    }

    /**
     * 押金详情
     * @param int $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function depositInfo(int $order_id)
    {
        $order = CarOrder::find($order_id);
        $order = $order ? $order->toArray() : [];
        if (!$order) throw new AdminException('未查询到订单信息');
        $take = CarOrderTake::find($order['take_id']);
        $take = $take ? $take->toArray() : [];
        $return = CarOrderReturn::find($order['return_id']);
        $return = $return ? $return->toArray() : [];
        $data['order_id'] = $order_id; // 订单ID
        $data['take_id'] = $take['id'];// 取车单ID
        $data['return_id'] = $return['id'];// 还车单ID
        $data['take_illegal_deposit'] = $take['illegal_deposit']??0; // 违章押金
        $data['take_deposit'] = $take['deposit']??0; // 车型押金
        $data['take_all_deposit_fee'] = $take['all_deposit_fee']??0; // 总押金
        $data['take_integral_fee'] = $take['integral_fee']??0; // 支付宝分抵押金
        $data['take_deposit_fee'] = $take['deposit_fee']??0; // 需支付押金
        $data['take_deposit_is_pay'] = $take['deposit_is_pay']??0; // 是否支付押金
        $data['take_deposit_pay_time'] = $take['deposit_pay_time']??0; // 押金支付时间
        $data['take_deposit_pay_time'] = $data['take_deposit_pay_time'] ? date('Y-m-d H:i:s', $data['take_deposit_pay_time']) : '暂无'; // 押金支付时间
        $data['take_deposit_pay_type'] = $take['deposit_pay_type']??0; // 押金支付方式
        $data['return_type'] = $return['return_type']??0; // 是否已支付
        $already_refund = CarOrderDepositRefund::where(['pay_no' => $take['take_no']])->sum('price');
        $may_refund = bcsub($take['deposit_fee'], $already_refund, 2);
        $data['may_refund'] = $may_refund;
        $data['illegal_remark'] = $return['illegal_remark'];
        return compact('data');
    }

    /**
     * 押金退款
     * @param int $order_id
     * @param array $data
     * @param array $op_user
     * @param int $op_user_type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function depositRefund(int $order_id, array $data, array $op_user, int $op_user_type)
    {
        $order = CarOrder::find($order_id);
        if (!$order) throw new AdminException('未查询到订单信息');
        if ($order['status'] < 30) throw new AdminException('当前订单状态不能退押金');
        $order = $order->toArray();
        $take = CarOrderTake::find($order['take_id']);
        if (!$take) throw new AdminException('未查询到取车信息');
        $take = $take->toArray();
        if (!$take['deposit_is_pay']) throw new AdminException('用户未支付押金，不可退款');
        $pay_type = [
            1 => 'alipay',
            2 => 'offline',
            3 => 'weixin'
        ];
        if ($take['deposit_pay_type'] != $pay_type[$data['return_type']]) throw new AdminException('退回方式与用户支付渠道不一致');
        $return = CarOrderReturn::find($order['return_id']);
        if (!$return) throw new AdminException('未查询到还车信息');
        $return = $return->toArray();
        // 获取押金可退款金额
        $already_refund = CarOrderDepositRefund::where(['pay_no' => $take['take_no']])->sum('price');
        $may_refund = bcsub($take['deposit_fee'], $already_refund, 2);
        if ($may_refund < $data['price']) throw new AdminException('输入的金额大于可退款金额');
        switch ($take['deposit_pay_type']) {
            case PayServices::WEIXIN_PAY:
                $opt = [
                    'pay_price' => $take['deposit_fee'],
                    'refund_price' => $data['price'],
                    'type' => 'trade_no',
                    'refund_id' => $take['deposit_trade_no'] . rand(100, 999)
                ];
                $out_trade_no = $take['deposit_trade_no'];
                MiniProgramService::payOrderRefund($out_trade_no, $opt);
                break;
            case PayServices::ALIAPY_PAY:

                break;
            case PayServices::OFFLINE_PAY:

                break;
        }
        $insert = [
            'pay_no' => $take['take_no'],
            'out_trade_no' => $opt['refund_id']??'',
            'price' => $data['price'],
            'pay_type' => 1,
            'content' => $data['content'],
            'add_time' => time(),
            'deposit_type' => $data['deposit_type']
        ];
        $res = CarOrderDepositRefund::create($insert);
        if (!$res) throw new AdminException('记录回写失败');
        if ($data['deposit_type'] == 1) {
            $illegal_deposit = bcadd($return['illegal_deposit'], $data['price'], 2);
            $illegal = [
                'illegal_deposit' => $illegal_deposit,
                'illegal_return_type' => $data['return_type'],
                'illegal_remark' => $data['illegal_remark']
            ];
            CarOrderReturn::where('id', $return['id'])->update($illegal);
        } else {
            $deposit = bcadd($return['deposit'], $data['price'], 2);
            $car_type = [
                'deposit' => $deposit,
                'return_type' => $data['return_type']
            ];
            CarOrderReturn::where('id', $return['id'])->update($car_type);
        }
        $title = '订单押金退款【' . $data['price'] . '】';
        BaseLogServices::addLog($take['id'], 2, $title, $op_user_type, $op_user['id'], $op_user['real_name'], 26);
        return '退款成功';
    }
}